package org.mech.sefer.client.mvp.spring.wtk;

import org.apache.pivot.beans.BXMLSerializer;
import org.mech.sefer.client.mvp.View;
import org.mech.sefer.client.mvp.wtk.BxmlView;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanExpressionException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * <p>
 * The BxmlViewInitializer is {@link BeanPostProcessor} that binds beans that
 * are annotated with {@link BxmlView} using apache pivot {@link BXMLSerializer}
 * </p>
 * <p>
 * Date: 27.4.2012 16:10:40
 * </p>
 * 
 * @author martin.krajc
 */
public class BxmlViewInitializer implements BeanPostProcessor {

	private String commonPath;

	@Override
	public Object postProcessBeforeInitialization(Object obj, String s)
			throws BeansException {
		if (obj instanceof View) {
			BxmlView bxmlView = obj.getClass().getAnnotation(BxmlView.class);
			if (bxmlView != null) {

				StringBuilder res = new StringBuilder();

				if (!bxmlView.useCommonPath()) {
					res.append('/');
					res.append(obj.getClass().getPackage().getName()
							.replace('.', '/'));
					res.append('/');
				} else {
					res.append(commonPath);
					res.append('/');
				}

				if (bxmlView.value() == null || bxmlView.value().isEmpty()) {
					res.append(obj.getClass().getSimpleName());
					res.append(".xml");
				} else {
					res.append(bxmlView.value());
				}

				try {

					final BXMLSerializer bxmlSerializer = new BXMLSerializer();
					bxmlSerializer.readObject(obj.getClass(), res.toString());
					bxmlSerializer.bind(obj);
					

				} catch (Exception e) {
					throw new BeanExpressionException("BXML Binding resource '"
							+ res.toString() + "' failed", e);
				}
			}
		}
		return obj;
	}

	@Override
	public Object postProcessAfterInitialization(Object obj, String s)
			throws BeansException {
		return obj;
	}

	public String getCommonPath() {
		return commonPath;
	}

	public void setCommonPath(String commonPath) {
		this.commonPath = commonPath;
	}

}
